package svg

import (
	"strings"

	"gosvg/dom"
)

type StyleBlock struct {
	selector string
	props    map[string]string
}

type StyleElement struct {
	groups []StyleBlock
}

type RawStyleElement struct {
	rawText string
}

func RawStyle(s string) *RawStyleElement {
	return &RawStyleElement{rawText: s}
}

func (e *RawStyleElement) XmlWrite(writer *dom.Writer) {
	str := "<style"

	val := strings.TrimSpace(e.rawText)

	if val == "" && !writer.Debug() {
		return
	} else if val == "" {
		str += "/>"
	} else {
		str += ">"
	}

	writer.IndentPrint(str)

	if val != "" {
		writer.NewLineOpt()
		writer.Indent()
		writer.IndentPrint(val)
		writer.Exdent()
		writer.NewLineOpt()
		writer.IndentPrint("</style>")
	}
}

func Style() *StyleElement {
	return &StyleElement{}
}

func (s *StyleElement) Block(selector string) *StyleBlock {
	if s.groups == nil {
		s.groups = make([]StyleBlock, 0)
	}

	k := StyleBlock{selector: selector, props: make(map[string]string)}

	s.groups = append(s.groups, k)

	return &k
}

func (k *StyleBlock) Prop(prop, val string) *StyleBlock {
	k.props[prop] = val
	return k
}

func (e *StyleElement) XmlWrite(writer *dom.Writer) {
	sep := ":"
	if writer.Debug() {
		sep = " : "
	}
	str := "<style"

	if e.groups != nil && len(e.groups) > 0 {
		str += ">"
		writer.IndentPrint(str)
		writer.NewLineOpt()
		writer.Indent()
		for _, val := range e.groups {
			toprint := val.selector
			if writer.Debug() {
				toprint += " "
			}

			toprint += "{"

			writer.IndentPrint(toprint)

			writer.Indent()
			first := true
			for key, val := range val.props {
				if !first {
					writer.Print(";")
				} else {
					first = false
				}
				writer.NewLineOpt()

				writer.IndentPrint(key + sep + val)
			}
			writer.Exdent()

			writer.NewLineOpt()
			writer.IndentPrint("}")
			writer.NewLineOpt()
		}
		writer.Exdent()
		writer.IndentPrint("</style>")
	} else {
		str += "/>"
		if writer.Debug() {
			writer.IndentPrint(str)
		}
	}
}
